#include "UPanel.h"

using namespace std;

RelativeControl::RelativeControl(TControl* Item, TRectangle rect)
{
	Rectangle = rect;
	control = Item;
}


TPanel::TPanel(TRectangle rect)
: TControl(rect)
{
	Color = TVector(0.8,0.8,0.8);
}

void TPanel::AddItem(TControl* Item)
{
	RelativeControl r = RelativeControl(Item, Item->BoundsRect());
	Controls.push_back(r);
}

void TPanel::MoveItem(int Index, TRectangle newPos)
{
	Controls[Index].control->setPos(TRectangle(
								newPos.Left 	+ BoundsRect().Left,
								newPos.Top 		+ BoundsRect().Top,
								newPos.Right 	+ BoundsRect().Right,
								newPos.Bottom 	+ BoundsRect().Bottom));
	Controls[Index].Rectangle = newPos;
}

void TPanel::RemoveItem(int Index)
{
	vector<RelativeControl>::iterator i = Controls.begin();
	i += Index;
	Controls.erase(i);
}

void TPanel::Draw()
{
	glColor3f(Color.x, Color.y, Color.z);
	glBegin(GL_QUADS);
		glVertex2i(BoundsRect().Left	, BoundsRect().Top);
		glVertex2i(BoundsRect().Left	, max(BoundsRect().Top, BoundsRect().Bottom));
		glVertex2i(max(BoundsRect().Right, BoundsRect().Left)	, max(BoundsRect().Top, BoundsRect().Bottom));
		glVertex2i(max(BoundsRect().Right, BoundsRect().Left)	, BoundsRect().Top);
	glEnd();
	glColor3f(0,0,0);
	glBegin(GL_LINES);
		glVertex2i(BoundsRect().Left - 1, BoundsRect().Top - 1);
		glVertex2i(BoundsRect().Left - 1, max(BoundsRect().Top, BoundsRect().Bottom) + 1);
		glVertex2i(max(BoundsRect().Right, BoundsRect().Left) + 1, max(BoundsRect().Top, BoundsRect().Bottom) + 1);
		glVertex2i(max(BoundsRect().Right, BoundsRect().Left) + 1, BoundsRect().Top - 1);
	glEnd();

	for (uint32 i = 0; i < Controls.capacity(); ++i)
	{
		Controls[i].control->Draw();
	}
}

void TPanel::setFocus(bool focus)
{

}

void TPanel::setPos(TRectangle rect)
{
	TControl::setPos(rect);
	for(uint32 i = 0; i < Controls.capacity(); ++i)
	{
		Controls[i].control->setPos(TRectangle( rect.Left + Controls[i].Rectangle.Left,
												rect.Top + Controls[i].Rectangle.Top,
												max(min(rect.Left + Controls[i].Rectangle.Right, rect.Right), rect.Left + Controls[i].Rectangle.Left),
												max(min(rect.Top + Controls[i].Rectangle.Bottom, rect.Bottom), rect.Top + Controls[i].Rectangle.Top)));
	}
}

TControl* TPanel::GetItem(int Index)
{
	return Controls[Index].control;
}
